package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.bo.GoodsCombineBo;
import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.service.AdminGoodsService;
import com.cskaoyan.market.util.MybatisUtil;
import com.cskaoyan.market.vo.BrandVo;
import com.cskaoyan.market.vo.CategoryVo;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminGoodsServiceImpl implements AdminGoodsService {
    // list方法
    @Override
    public List<MarketGoods> list(String page, String limit, String goodsSn, String name, String sort, String order, String goodsId) {
        SqlSession session = MybatisUtil.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        // 设置商品id查询条件
        if (!StringUtils.isEmpty(goodsId)) {
            criteria.andIdEqualTo(Integer.parseInt(goodsId));
        }
        // 设置商品编号查询条件
        if (!StringUtils.isEmpty(goodsSn)) {
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        // 设置商品名称的模糊查询
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        // 设置排序
        marketGoodsExample.setOrderByClause(sort + " " + order);
        // 设置分页
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketGoods> marketGoods = mapper.selectByExample(marketGoodsExample);
        // 提交事务，关闭连接
        session.commit();
        session.close();
        return marketGoods;
    }

    // delete方法-删除方法
    @Override
    public boolean delete(String id) {
        SqlSession session = MybatisUtil.getSession();
        MarketGoodsMapper mapper = session.getMapper(MarketGoodsMapper.class);
        mapper.logicalDeleteByPrimaryKey(Integer.parseInt(id));
        session.commit();
        session.close();
        return true;
    }

    // detail方法-展示商品细节
    @Override
    public Map<String, Object> detail(String id) {
        SqlSession session = MybatisUtil.getSession();
        // 获得mapper
        MarketGoodsMapper marketGoodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketCategoryMapper categoryMapper = session.getMapper(MarketCategoryMapper.class);
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsProductMapper productMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsSpecificationMapper specificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);

        // 创建返回的Map
        Map<String, Object> map = new HashMap<>();

        // 封装goods信息
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKeyWithLogicalDelete(Integer.parseInt(id), false);
        map.put("goods", marketGoods);

        // 封装category数组
        Integer categoryId = marketGoods.getCategoryId();
        MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(categoryId);
        int[] category = {marketCategory.getPid(), categoryId};
        map.put("categoryIds", category);

        // 封装attribute List
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        attributeExample.or().andGoodsIdEqualTo(Integer.parseInt(id));
        List<MarketGoodsAttribute> marketGoodsAttributes = attributeMapper.selectByExample(attributeExample);
        map.put("attributes", marketGoodsAttributes);

        // 封装product List
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.or().andGoodsIdEqualTo(Integer.parseInt(id));
        List<MarketGoodsProduct> marketGoodsProducts = productMapper.selectByExample(productExample);
        map.put("products", marketGoodsProducts);


        // 封装specification List
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        specificationExample.or().andGoodsIdEqualTo(Integer.parseInt(id));
        List<MarketGoodsSpecification> marketGoodsSpecifications = specificationMapper.selectByExample(specificationExample);
        map.put("specifications", marketGoodsSpecifications);

        session.commit();
        session.close();
        return map;
    }

    // catAndBrand方法
    @Override
    public Map<String, Object> catAndBrand() {
        // 获得mapper
        SqlSession session = MybatisUtil.getSession();
        MarketBrandMapper brandMapper = session.getMapper(MarketBrandMapper.class);
        MarketCategoryMapper categoryMapper = session.getMapper(MarketCategoryMapper.class);

        // 创建返回的Map
        Map<String, Object> map = new HashMap<>();

        // 封装brandList
        List<MarketBrand> marketBrands = brandMapper.selectByExampleSelective(new MarketBrandExample(), MarketBrand.Column.id, MarketBrand.Column.name);
        List<BrandVo> brandVoList = new ArrayList<>();
        for (MarketBrand marketBrand : marketBrands) {
            brandVoList.add(new BrandVo(marketBrand.getName(), marketBrand.getId()));
        }
        map.put("brandList", brandVoList);

        // 封装categoryList
        List<MarketCategory> marketCategories = categoryMapper.selectByExample(new MarketCategoryExample());
        Map<Integer, List<MarketCategory>> categoryGroupByPidMap = groupByPid(marketCategories);
        List<MarketCategory> categoryList = categoryGroupByPidMap.get(0);
        List<CategoryVo> list = new ArrayList<>();
        for (MarketCategory marketCategory : categoryList) {
            CategoryVo categoryVo = new CategoryVo(marketCategory.getId(), marketCategory.getName(), null);
            // 寻找下一级的信息
            List<MarketCategory> smallCateList = categoryGroupByPidMap.get(marketCategory.getId());
            List<CategoryVo> categoryVos = new ArrayList<>();
            for (MarketCategory smallCate : smallCateList) {
                CategoryVo sCate = new CategoryVo(smallCate.getId(), smallCate.getName(), null);
                categoryVos.add(sCate);
            }
            categoryVo.setChildren(categoryVos);
            list.add(categoryVo);
        }
        map.put("categoryList", list);

        session.commit();
        session.close();
        return map;
    }

    // update方法
    @Override
    public void update(GoodsCombineBo goodsCombineBo) {
        // 获得session
        SqlSession session = MybatisUtil.getSession();
        MarketGoodsMapper marketGoodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsProductMapper marketGoodsProductMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsAttributeMapper marketGoodsAttributeMapper
                = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsSpecificationMapper marketGoodsSpecificationMapper =
                session.getMapper(MarketGoodsSpecificationMapper.class);

        // 更新goods
        MarketGoods goods = goodsCombineBo.getGoods();
        goods.setUpdateTime(LocalDateTime.now());
        marketGoodsMapper.updateByPrimaryKeyWithBLOBs(goods);
        // 更新goods_attribute (只能修改，不能新增，待解决)
        for (MarketGoodsAttribute attribute : goodsCombineBo.getAttributes()) {
            attribute.setUpdateTime(LocalDateTime.now());
            marketGoodsAttributeMapper.updateByPrimaryKey(attribute);
        }
        // 更新goods_product
        for (MarketGoodsProduct product : goodsCombineBo.getProducts()) {
            product.setUpdateTime(LocalDateTime.now());
            marketGoodsProductMapper.updateByPrimaryKey(product);
        }
        // 更新goods_specification
        for (MarketGoodsSpecification specification : goodsCombineBo.getSpecifications()) {
            specification.setUpdateTime(LocalDateTime.now());
            marketGoodsSpecificationMapper.updateByPrimaryKey(specification);
        }
        session.commit();
        session.close();
    }

    @Override
    public boolean create(MarketGoods goods, List<MarketGoodsAttribute> attributes,
                          List<MarketGoodsSpecification> specifications, List<MarketGoodsProduct> products) {
        // 获得Mapper
        SqlSession session = MybatisUtil.getSession();
        MarketGoodsMapper goodsMapper = session.getMapper(MarketGoodsMapper.class);
        MarketGoodsAttributeMapper attributeMapper = session.getMapper(MarketGoodsAttributeMapper.class);
        MarketGoodsProductMapper productMapper = session.getMapper(MarketGoodsProductMapper.class);
        MarketGoodsSpecificationMapper specificationMapper = session.getMapper(MarketGoodsSpecificationMapper.class);

        try {
            // 添加goods
            goods.setUpdateTime(LocalDateTime.now());
            goods.setAddTime(LocalDateTime.now());
            goodsMapper.insertSelective(goods);

            // 添加attribute
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setAddTime(LocalDateTime.now());
                attribute.setUpdateTime(LocalDateTime.now());
                attributeMapper.insertSelective(attribute);
            }
            // 添加products
            for (MarketGoodsProduct product : products) {
                product.setGoodsId(goods.getId());
                product.setUpdateTime(LocalDateTime.now());
                product.setAddTime(LocalDateTime.now());
                productMapper.insertSelective(product);
            }
            // 添加specifications
            for (MarketGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setUpdateTime(LocalDateTime.now());
                specification.setAddTime(LocalDateTime.now());
                specificationMapper.insertSelective(specification);
            }
        } catch (Exception e) {
            session.rollback();
            return false;
        }
        session.commit();
        session.close();
        return true;
    }

    // 根据pid将category分发进map
    private Map<Integer, List<MarketCategory>> groupByPid(List<MarketCategory> marketCategories) {
        Map<Integer, List<MarketCategory>> categoryGroupByPid = new HashMap<>();
        for (MarketCategory category : marketCategories) {
            List<MarketCategory> categories = categoryGroupByPid.get(category.getPid());
            if (categories == null) {
                categories = new ArrayList<>();
                categoryGroupByPid.put(category.getPid(), categories);
            }
            categories.add(category);
        }
        return categoryGroupByPid;
    }
}
